/*
 @Date: 2022/5/10
 @Desc: 腾讯的api
 */

import UIKit
import Alamofire
import CommonCrypto

enum TXApi: IPRouter {
    
    var baseUrl: String {
        return "https://bda.tencentcloudapi.com"
    }
    
    var path: String {
        return ""
    }
    
    var parameters: [String : Any]? {
        switch self {
            case .bodyAnalysis(let data):
                return ["Image": data]
        }
    }
    
    func configureParas() -> [String : Any] {
        return ["":""]
    }
    
    
    private var header: HTTPHeaders? {
        let dict = configureHeader()
        return HTTPHeaders.init(dict)
    }
    
    /// hmac sha1 加密
    private func hmacsha256(_ key: String,_ target: String)-> String? {
        let op = kCCHmacAlgSHA256
        guard let cKey = key.cString(using: .utf8) else { return nil }
        guard let cTarget = target.cString(using: .utf8) else { return nil }
        var result = [CUnsignedChar](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
        CCHmac(CCHmacAlgorithm(op), cKey, strlen(cKey), cTarget, strlen(cTarget), &result)
        let hmacData: NSData = NSData(bytes: result, length: Int(CC_SHA256_DIGEST_LENGTH))
        let hmacBase64 = hmacData.base64EncodedString(options: .lineLength76Characters)
        return hmacBase64
    }
    
    /// 验证信息
    private func fetchAuthorization(_ date: Date)-> String?{
        // 时间
        let dateStr = "\(date.timeIntervalSince1970 / 1000)"
        let dateForm = DateFormatter()
        dateForm.dateFormat = "yyyy-MM-dd"
        let df = dateForm.string(from: date)
        
        // body参数
        guard let body = parameters else { return nil }
        do {
            let data = try JSONSerialization.data(withJSONObject: body, options: .sortedKeys)
            guard let json = String.init(data: data, encoding: .utf8) else { return nil }
            guard let hashJson = json.shaHash() else { return nil }
            // 1.拼接规范请求串
            let HTTPRequestMethod = "POST"
            let CanonicalURI = "/"
            let CanonicalQueryString = ""
            let CanonicalHeaders = "content-type:application/json; charset=utf-8\nhost:bda.tencentcloudapi.com"
            let SignedHeaders = "content-type;host"
            let HashedRequestPayload = hashJson
            
            let canonicalRequest = HTTPRequestMethod + "\n" +
            CanonicalURI + "\n" +
            CanonicalQueryString + "\n" +
            CanonicalHeaders + "\n" +
            SignedHeaders + "\n" +
            HashedRequestPayload + "\n"
            
            // 2.拼接待签名字符串
            let Algorithm = "TC3-HMAC-SHA256"
            let RequestTimestamp = dateStr
            let CredentialScope = "\(df)/bda/tc3_request"
            guard let HashedCanonicalRequest = canonicalRequest.shaHash() else {
                return nil
            }
            let StringToSign = Algorithm + "\n" + RequestTimestamp + "\n" + CredentialScope + "\n" + HashedCanonicalRequest
            
            
            // 3.计算签名
            let SecretKey = "C8oEOK0RcXCcmgKiqseAQQCiyxg8JDrE"
            let SecretId = "AKIDHOGrBF4brqY0A3f16uRiokRs40g6IEuK"
            guard let SecretDate = hmacsha256("TC3" + SecretKey, dateStr) else {
                return nil
            }
            guard let SecretService = hmacsha256(SecretDate, "bda") else {
                return nil
            }
            guard let SecretSigning = hmacsha256(SecretService, "tc3_request") else {
                return nil
            }
            guard let Signature = hmacsha256(SecretSigning, StringToSign) else {
                return nil
            }
            
            
            
        } catch let info {
            print("序列化失败--\(info)")
        }
        return nil
    }
    
    /*
     SecretKey = "Gu5t9xGARNpq86cd98joQYCN3*******"
     SecretDate = HMAC_SHA256("TC3" + SecretKey, Date)
     SecretService = HMAC_SHA256(SecretDate, Service)
     SecretSigning = HMAC_SHA256(SecretService, "tc3_request")
     */
    
    
    /// 配置请求头
    private func configureHeader()->[String: String] {
        let date = Date()
        let dateStr = "\(date.timeIntervalSince1970 / 1000)"
        
        let dateForm = DateFormatter()
        dateForm.dateFormat = "yyyy-MM-dd"
        let ds = dateForm.string(from: date)
        
        let host = "bda.tencentcloudapi.com"
        
        let author = "TC3-HMAC-SHA256" + " " + "Credential=AKIDHOGrBF4brqY0A3f16uRiokRs40g6IEuK/\(ds)/bda/tc3_request,SignedHeaders=content-type;host,Signature="
        
        
        return ["Content-Type":"application/json",
                "Host":host,
                "X-TC-Action":"SegmentPortraitPic",
                "X-TC-Timestamp":dateStr,
                "X-TC-Version":"2020-03-24",
                "X-TC-Region":"ap-beijing",
                "Authorization":author]
    }
    
    func asURLRequest() throws -> URLRequest {
        let url = try baseUrl.asURL()
        let urlRequest =  try URLRequest.init(url: url, method: .post, headers: header)
        return try URLEncoding.default.encode(urlRequest, with: nil)
    }
    
    /// 腾讯人体分析
    case bodyAnalysis(_ base64Image: String)
    
}

